﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ExpenseSystem.Model;
using ExpenseSystem.Fether;
using ExpenseSystem.DataUpdater;
using ExpenseSystem.Common;
using ExpenseSystem.DataUpdater.Validation;

namespace ExpenseSystem.Core.UserModules
{
    public class UserUpdaterRegister
    {
        int rows;
        public SystemDataUpdater<UserModel> GetUserUpdater()
        {
            SystemDataUpdater<UserModel> systemDataUpdater = new SystemDataUpdater<UserModel>();
            systemDataUpdater.DataUpdating += DataNotSpaceValid;
            systemDataUpdater.DataUpdating += SingletonValid;
            systemDataUpdater.DataDeleting += CheckAvaliable;
            return systemDataUpdater;
        }
        private void CheckAvaliable(object sender, DataValidationEventArgs<UserModel> e)
        {
            EmployeeFetcher employeeFetcher = new EmployeeFetcher();
            int result = employeeFetcher.ListEmployeeByUser(e.Delete.AutoId,out rows).Count;
            if (result>0)
            {
                e.Cancle = true;
                e.Message = String.Format("[{0}]正在被员工信息占用，不能删除", e.Delete.Name);
            }
        }

        private void SingletonValid(object sender, DataValidationEventArgs<UserModel> e)
        {
            UserFetcher userFetcher = new UserFetcher();
            string message = "";
            UserModel user = userFetcher.GetByCode( e.Insert.Code, out message);
            if (user != null && user.AutoId != e.Insert.AutoId)
            {
                e.Cancle = true;
                message = String.Format("登录号[{0}]已被用户[{1}]占用", user.Code, user.Name);
                return;
            }
        }

        private void DataNotSpaceValid(object sender, DataValidationEventArgs<UserModel> e)
        {
            if (String.IsNullOrWhiteSpace(e.Insert.Code))
            {
                e.Message = "用户名不能为空";
                e.Cancle = true;
                return;
            }
            if (String.IsNullOrWhiteSpace(e.Insert.Name))
            {
                e.Message = "姓名不能为空";
                e.Cancle = true;
                return;
            }
        }
    }
}
